package com.example.coursedesign.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.SearchView.OnCloseListener;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.coursedesign.R;
import com.example.coursedesign.ui.home.adapter.CategoryAdapter;
import com.example.coursedesign.ui.home.dao.MedicineDao;
import com.example.coursedesign.ui.home.entity.Medicine;

import java.util.List;
import java.util.Map;

public class searchMedicine extends AppCompatActivity implements CategoryAdapter.OnMedicineClickListener {
    private static final String TAG = "searchMedicine";
    private RecyclerView categoryRecyclerView;
    private CategoryAdapter adapter;
    private MedicineDao medicineDao;
    private Map<String, List<Medicine>> allMedicinesByCategory; // 保存所有药品分类用于恢复原始数据
    private SearchView searchView;
    private Button searchButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_medicine);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        categoryRecyclerView = findViewById(R.id.categoryRecyclerView);
        categoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        medicineDao = new MedicineDao();

        searchView = findViewById(R.id.searchView);
        searchButton = findViewById(R.id.searchButton);

        // 设置搜索按钮点击监听器
        searchButton.setOnClickListener(v -> {
            String query = searchView.getQuery().toString();
            if (!query.isEmpty()) {
                searchMedicines(query);
            } else {
                Toast.makeText(this, "请输入要查询的关键字", Toast.LENGTH_SHORT).show();
            }
        });

        // 监听 SearchView 的关闭事件
        searchView.setOnCloseListener(() -> {
            restoreOriginalData();
            return false; // 返回 false 表示允许关闭
        });

        // 监听 SearchView 的文本变化事件
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false; // 不处理提交事件，由按钮处理
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.isEmpty()) {
                    restoreOriginalData(); // 如果文本为空，则恢复原始数据
                }
                return true;
            }
        });

        loadMedicines();
    }

    private void loadMedicines() {
        new Thread(() -> {
            allMedicinesByCategory = medicineDao.getAllMedicinesGroupedByCategory();
            runOnUiThread(() -> {
                if (allMedicinesByCategory.isEmpty()) {
                    Toast.makeText(this, "没有找到任何药品", Toast.LENGTH_SHORT).show();
                } else {
                    adapter = new CategoryAdapter(allMedicinesByCategory, this);
                    categoryRecyclerView.setAdapter(adapter);
                }
            });
        }).start();
    }

    private void searchMedicines(String query) {
        new Thread(() -> {
            List<String> categories = getAllCategories();
            if (categories.contains(query)) { // 如果查询的是类别
                Map<String, List<Medicine>> categoryResults = medicineDao.searchMedicinesByCategory(query);
                runOnUiThread(() -> {
                    if (adapter != null) {
                        adapter.updateData(categoryResults); // 更新为分类显示
                    }
                });
            } else {
                List<Medicine> searchResults = medicineDao.searchMedicinesByName(query);
                runOnUiThread(() -> {
                    if (adapter != null) {
                        adapter.updateData(searchResults); // 更新为扁平化列表显示
                    }
                });
            }
        }).start();
    }

    private List<String> getAllCategories() {
        return medicineDao.getAllCategories();
    }

    private void restoreOriginalData() {
        if (adapter != null && allMedicinesByCategory != null) {
            adapter.updateData(allMedicinesByCategory); // 恢复原始分类数据
        }
    }

    @Override
    public void onMedicineClick(Medicine medicine) {
        Intent intent = new Intent(this, MedicineDetail.class);
        intent.putExtra("medicine_id", medicine.getId());
        startActivity(intent);
    }

    @Override
    public boolean onSupportNavigateUp() {
        setResult(AppCompatActivity.RESULT_OK);
        finish();
        return true;
    }

    @Override
    public void onBackPressed() {
        setResult(AppCompatActivity.RESULT_OK);
        super.onBackPressed();
    }
}